package com.zmn.oms.business.impl.work;

import com.alibaba.fastjson.JSON;
import com.vdurmont.emoji.EmojiParser;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.company.CompanyDRO;
import com.zmn.base.common.data.dubbo.interfaces.company.CompanyListRemoteService;
import com.zmn.base.engineer.common.constants.DubboConsts;
import com.zmn.base.engineer.common.dro.supervisor.SupervisorViewDRO;
import com.zmn.base.engineer.dubbo.interfaces.supervisor.EngineerSupervisorListRemoteService;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.dms.common.dto.activity.dio.LateCompensationCalculationDIO;
import com.zmn.dms.common.dto.activity.dro.LateCompensationCalculationDRO;
import com.zmn.dms.dubbo.interfaces.activity.ActivityInfoListRemoteService;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.discount.OrderDiscountBService;
import com.zmn.oms.business.interfaces.serviceitem.OrderServiceItemBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.OrderWorkAmountBService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dro.orderpay.OrderPayResultDRO;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.dto.work.modify.CheckQuotationTypeOrderDTO;
import com.zmn.oms.model.dto.work.workamount.WorkAmountDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.uuc.common.dio.user.UserRegisterByThirdAccountDIO;
import com.zmn.uuc.dubbo.interfaces.user.UserRegisterRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：录入工单业务实现
 *
 * @author liuying
 * @date 2018/11/:02
 */
@Slf4j
@Service
public class OrderWorkBServiceImpl implements OrderWorkBService {

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ChannelListRemoteService channelListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private CompanyListRemoteService companyListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserRegisterRemoteService userRegisterRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private EngineerSupervisorListRemoteService engineerSupervisorListRemoteService;
    @Reference(version = com.zmn.dms.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private ActivityInfoListRemoteService activityInfoListRemoteService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderServiceItemBService orderServiceItemBService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private BaseCodeService baseCodeService;
    @Autowired
    private OrderWorkAmountBService orderWorkAmountBService;
    @Autowired
    private OrderDiscountBService orderDiscountBService;
    @Autowired
    private OrderWarrantyService orderWarrantyService;
    @Autowired
    private OrderMemberService orderMemberService;
    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private ServItemBService servItemBService;

    @Override
    public OrderBO findOrderWork(Long orderId, Long workId) {
        OrderBO orderBO = new OrderBO();
        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, workId);
        orderBO.setOrderWork(orderWork);
        orderBO.setOrder(orderService.findOrderByKey(orderId));
        orderBO.setOrderProductList(orderProductService.listOrderProductByOrderId(orderId));
        orderBO.setOrderDetail(orderDetailService.findOrderDetailByKeySrcMaster(orderId));
        if (Objects.equals(orderBO.getOrderWork().getMember(), GlobalConsts.YES)) {
            orderBO.setOrderMember(orderMemberService.findMemberByKey(orderWork.getOrderId()));
        }
        return orderBO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderWork(OrderWork orderWork) {
        if (StringUtil.isNotBlank(orderWork.getCurrentRemark())) {
            orderWork.setCurrentRemark(EmojiParser.parseToUnicode(orderWork.getCurrentRemark()));
        }
        orderWork.setUpdateTime(DateUtil.getNow());
        orderWorkService.updateOrderWorkByKey(orderWork);
    }

    @Override
    public void processOrderWork(OrderDTO orderDTO) {
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderWork dbOrderWork = orderDTO.getDbOrderWork();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        Order order = orderDTO.getOrder();
        Integer type = Optional.ofNullable(orderWork.getType()).orElse(order.getType());
        orderWork.setStandardPrice(GlobalConsts.YES);
        orderWork.setBizType(order.getBizType());
        // 维修安装才有标准收费

        // region 订单-->工单
        if (orderWork.getCityId() == null) {
            if (order.getCityId() != null) {
                orderWork.setCityId(order.getCityId());
            }
            else if (order.getNaturalCityId() != null) {
                orderWork.setCityId(order.getNaturalCityId());
            }
        }

        // 订单ID
        orderWork.setOrderId(order.getOrderId());
        // 公司处理
        if (!Objects.isNull(dbOrderWork)) {
            orderWork.setCompanyId(dbOrderWork.getCompanyId());
        } else {
            orderWork.setCompanyId(order.getCompanyId());
        }
        // 一级组织id
        orderWork.setOrgOneId(order.getOrgOneId());
        // 二级组织id
        orderWork.setOrgTwoId(order.getOrgTwoId());
        // 三级组织id
        orderWork.setOrgThreeId(order.getOrgThreeId());
        // 四级组织id
        orderWork.setOrgFourId(order.getOrgFourId());
        // 城市id
        orderWork.setCityId(order.getCityId());
        // 行政城市id
        orderWork.setNaturalCityId(order.getNaturalCityId());
        // 预约时间
        orderWork.setDutyTime(order.getDutyTime());
        // 平台标志
        orderWork.setPlat(order.getPlat());
        orderWork.setPlatWork(order.getPlatWork());
        // 测试单
        orderWork.setTest(order.getTest());

        // 冗余产品信息
        orderWork.setServCategId(orderDetail.getServCategId());
        orderWork.setCategId(orderDetail.getCategId());
        orderWork.setCategOneId(orderDetail.getCategOneId());
        orderWork.setProductGroupId(orderDetail.getProductGroupId());
        orderWork.setProductId(orderDetail.getProductId());
        orderWork.setCurrentRemark(orderDetail.getRemark());

        // 前端产品冗余
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        if (!Objects.equals(type, OrderConsts.ORDER_TYPE_REFUND) && !Objects.equals(type, OrderConsts.ORDER_TYPE_COMPENSATE)) {
            OrderProduct orderProduct = orderProductList.get(0);
            orderWork.setShowCategId(orderProduct.getShowCategId());
            orderWork.setShowCategOneId(orderProduct.getShowCategOneId());
            orderWork.setShowProductId(orderProduct.getShowProductId());
        }

        // 来源
        orderWork.setSourceType(order.getSourceType());
        // 用户ID
        orderWork.setUserId(order.getUserId());

        // endregion

        // 返修单处理
        if (Objects.equals(type, OrderConsts.ORDER_TYPE_REWORK)) {
            // 查询原单
            OrderWork reworkOrderWork = orderWorkService.findOrderWorkByKey(orderWork.getReworkId(), orderWork.getReworkId());
            if (reworkOrderWork != null) {
                Long originalId = NumberUtil.isNullOrZero(reworkOrderWork.getOriginalId()) ? orderWork.getReworkId() : reworkOrderWork.getOriginalId();
                orderWork.setOriginalId(originalId);
                // 返修新单建返修单处理源单id
                if (Objects.equals(reworkOrderWork.getType(), OrderConsts.ORDER_TYPE_NEW)
                        && Objects.equals(reworkOrderWork.getChannelId(), OrderConsts.CHANNEL_ID_PLAT_REWORK_NEW_ORDER)
                        && NumberUtil.isNotNullOrZero(reworkOrderWork.getOriginalId())) {
                    orderWork.setOriginalId(orderWork.getReworkId());
                }

                // 保存原单工程师
                orderWork.setReworkMasterId(reworkOrderWork.getMasterId());

            }
        } else if (Objects.equals(type, OrderConsts.ORDER_TYPE_NEW)) {

            // 新单
            orderWork.setReworkId(null);
            orderWork.setReworkMasterId(null);
        }

        if (Objects.equals(type, OrderConsts.ORDER_TYPE_REFUND) || Objects.equals(type, OrderConsts.ORDER_TYPE_COMPENSATE)) {
            // 退款单ID特殊处理
            orderWork.setWorkId(null);
            // 录入时间、预约时间、完成时间一致
            orderWork.setReceiveTime(DateUtil.getNow());
            orderWork.setDutyTime(orderWork.getReceiveTime());
//            orderWork.setCompleteTime(orderWork.getReceiveTime());
            orderWork.setOriginalAmount(0);
            orderWork.setMasterAmount(0);
            orderWork.setDiscountAmount(0);
            orderWork.setPrepayAmount(0);
        } else {
            orderWork.setStatus(order.getStatus());
            orderWork.setResultStatus(order.getResultStatus());
            orderWork.setOriginalAmount(order.getOriginalAmount());
            orderWork.setTotalAmount(order.getTotalAmount());
            orderWork.setMasterAmount(order.getMasterAmount());
            orderWork.setDiscountAmount(order.getDiscountAmount());
            orderWork.setChannelPrepayAmount(order.getChannelPrepayAmount());
            orderWork.setChannelPrepayStatus(order.getChannelPrepayStatus());
            orderWork.setPayStatus(order.getPayStatus());
        }

        orderWork.setType(type);

        // region 冗余字段处理

        // 处理工程师推荐渠道
        this.processEngineerRecommendChannel(orderWork, orderDetail.getTelephone());

        // 渠道
        ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(orderWork.getChannelId());
        ChannelDRO channelDRO = channelResponseDTO.getData();
        if (channelDRO != null) {
            // 合同模式
            orderWork.setBizModeSource(channelDRO.getContractModel());

            orderWork.setChannelName(channelDRO.getName());
            orderWork.setChannelAnotherName(StringUtils.defaultString(channelDRO.getAnotherName()));
            orderWork.setChannelOneId(channelDRO.getPlat());
            orderWork.setChannelTwoId(channelDRO.getParentId());
            // orderWork.setChannelTypeId(channelDRO.getTypeId());
        } else {
            log.error("[{}]Remote接口未找到渠道", orderWork.getChannelId());
        }

        // 处理来源渠道
        Integer channelId = orderWork.getChannelId();
        Integer sourceChannelId = orderWork.getSourceChannelId();
        // 如果来源渠道为空 则用下单渠道,或来源渠道=下单渠道，则设置相同
        if (NumberUtil.isNullOrZero(orderWork.getSourceChannelId()) || Objects.equals(channelId, sourceChannelId)) {
            orderWork.setSourceChannelId(orderWork.getChannelId());
            orderWork.setSourceChannelOneId(orderWork.getChannelOneId());
            orderWork.setSourceChannelTwoId(orderWork.getChannelTwoId());
        } else {
            ResponseDTO<ChannelDRO> channelDROResponseDTO = channelListRemoteService.getByChannelId(sourceChannelId);
            log.info("#oms#sourceChannel#sourceChannelId={}，获取来源渠道getByChannelId信息出参【{}】", sourceChannelId, JSON.toJSONString(channelDROResponseDTO));
            ChannelDRO channel = channelDROResponseDTO.getData();
            orderWork.setSourceChannelOneId(channel.getPlat());
            orderWork.setSourceChannelTwoId(channel.getParentSourceId());
        }

        // 公司名称
        if (!NumberUtil.isNullOrZero(orderWork.getCompanyId())) {
            log.info("#insertRefund 查找子公司信息：入参：{}", orderWork.getCompanyId());
            ResponseDTO<com.zmn.base.common.data.common.dro.company.CompanyDRO> companyResponseDTO = companyListRemoteService.getCompanyDROById(orderWork.getCompanyId());
            log.info("#insertRefund 查找子公司信息：出参：{}", JSON.toJSONString(companyResponseDTO));
            if (companyResponseDTO.getData() != null) {
                CompanyDRO companyDRO = companyResponseDTO.getData();
                orderWork.setCompanyName(companyDRO.getName());

                // 组织架构
                orderWork.setOrgOneId(companyDRO.getPlat());
                orderWork.setOrgTwoId(companyDRO.getOrgTwoId());
                orderWork.setOrgThreeId(companyDRO.getOrgThrId());
                orderWork.setOrgFourId(order.getManageCompanyId());
            } else {
                log.error("[{}]Remote接口未找到公司", orderWork.getCompanyId());
                orderWork.setCompanyName(StringUtils.defaultString(orderWork.getCompanyName()));
            }
        } else {
            if (orderDTO.getDbOrderWork() != null) {
                orderWork.setCompanyName(StringUtils.defaultString(orderDTO.getDbOrderWork().getCompanyName()));
            } else {
                orderWork.setCompanyName(StringUtils.defaultString(orderWork.getCompanyName()));
            }
        }

        // 预约时间与下次联系时间互斥
        if (Objects.nonNull(orderWork.getDutyTime())) {
            orderWork.setNextContactTime(null);
            orderWork.setDutyStatus(OrderDutyConsts.DUTY_STATUS_SUCCESS);
        }

        // 处理预约失败默认值
        if (Objects.equals(OrderDutyConsts.DUTY_STATUS_SUSPEND, orderWork.getDutyStatus()) ||
                Objects.equals(OrderDutyConsts.DUTY_STATUS_FAIL, orderWork.getDutyStatus())) {
            if (Objects.isNull(orderWork.getNextContactTime())) {
                orderWork.setNextContactTime(DateUtil.parse(DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), 5),"yyyy-MM-dd 14:00:00")));
            }
        }

        // 录单人信息
        if (NumberUtil.isNullOrZero(orderWork.getReceiverType())) {
            orderWork.setReceiverType(orderDTO.getOperatorType());
        }
        if (NumberUtil.isNullOrZero(orderWork.getReceiverId())) {
            orderWork.setReceiverId(orderDTO.getOperatorId());
        }
        // endregion

        // 优先使用前端传递的工单服务类型
        orderWork.setServItemType(orderDTO.getOriginServItemType());
        if (NumberUtil.isNullOrZero(orderWork.getServItemType())) {
            CheckQuotationTypeOrderDTO checkQuotationTypeOrderDTO = BeanMapper.map(orderWork, CheckQuotationTypeOrderDTO.class);
            if (Objects.nonNull(dbOrderWork)) {
                checkQuotationTypeOrderDTO.setCompanyId(dbOrderWork.getCompanyId());
                checkQuotationTypeOrderDTO.setMasterId(dbOrderWork.getMasterId());
                checkQuotationTypeOrderDTO.setBeforeServItemType(dbOrderWork.getServItemType());
            }
            log.info("[{}]修改计价类型2[{}]", orderWork.getWorkId(), checkQuotationTypeOrderDTO);
            Integer servItemType = servItemBService.getServItemType(checkQuotationTypeOrderDTO);
            Integer oldServiceItemType = orderDTO.getDbOrderWork() != null ? orderDTO.getDbOrderWork().getServItemType() : null;
            log.info("[{}]修改计价类型2，旧类型[{}]-->新类型[{}]", orderWork.getWorkId(), oldServiceItemType, servItemType);
            orderWork.setServItemType(servItemType);
        }

        // servItemType==5的修改成4，并且标识一口价（一口价订单需求兼容app走计价器3.0流程）
        if (Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)) {
            orderWork.setServItemType(OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
            orderWork.setFinalPrice(GlobalConsts.YES);
        }else {
            orderWork.setFinalPrice(GlobalConsts.NO);
        }

        // 新单迟到补偿
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) || Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
            // 记录迟到补偿的活动id
            LateCompensationCalculationDIO lateCompensationCalculationDIO = new LateCompensationCalculationDIO();
            lateCompensationCalculationDIO.setPlat(orderWork.getPlat());
            lateCompensationCalculationDIO.setChannelId(orderWork.getChannelId());
            lateCompensationCalculationDIO.setCityId(orderWork.getCityId());
            lateCompensationCalculationDIO.setProductId(orderWork.getShowProductId());
            lateCompensationCalculationDIO.setOrderId(orderWork.getOrderId());
            lateCompensationCalculationDIO.setUserId(orderWork.getUserId());
            if (orderWork.getOriginalAmount() != null) {
                lateCompensationCalculationDIO.setOrderAmount(new BigDecimal(orderWork.getOriginalAmount()));
            }
            try {
                ResponseDTO<LateCompensationCalculationDRO> lateCompensationCalculation = activityInfoListRemoteService.getLateCompensationCalculation(lateCompensationCalculationDIO);
                log.info("{}--获取迟到补偿activityInfoListRemoteService#getLateCompensationCalculation，入参[{}] 出参[{}]", orderWork.getOrderId(), lateCompensationCalculationDIO, JSON.toJSONString(lateCompensationCalculation));
                if (lateCompensationCalculation.isSuccess() && lateCompensationCalculation.getData() != null) {
                    orderWork.setDiscountActivityId(lateCompensationCalculation.getData().getActivityId());
                }
            } catch (Exception e) {
                log.error("获取迟到补偿:" + e.getMessage(), e);
            }
        }
    }

    /**
     * 当下单渠道为工程师推荐A/B、川南工程师推荐且下单类型为新单时
     * 下单手机号在本次下单前的72小时内在平台渠道B系（B01-B15）有下过单，则将下单渠道置为对应的平台渠道B系
     * @param orderWork
     * @param phone
     * @return
     */
    private void processEngineerRecommendChannel(OrderWork orderWork, String phone) {
        if (StringUtil.isBlank(phone)) {
            return;
        }

        // 不是师傅加单返回
        if (!Objects.equals(orderWork.getRecommenderType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)) {
            return;
        }

        if (OrderConsts.ENGINEER_RECOMMEND_CHANNEL_LIST.contains(orderWork.getChannelId())) {
            OrderWorkQuery query = new OrderWorkQuery();
            query.setConcatPhone(phone);
            query.setSingleWorkType(OrderConsts.ORDER_TYPE_NEW);
            query.setChannelIdList(OrderConsts.PLAT_CHANNEL_B_LIST);
            Date now = DateUtil.getNow();
            Date beforeThreeDay = DateUtil.getBaseDefer(now,0,0,-3,0,0, 0);
            query.setReceiveTime(DateUtil.dateFormatToString(beforeThreeDay, DateUtil.FORMAT_DEFAULT) + "," + DateUtil.dateFormatToString(now, DateUtil.FORMAT_DEFAULT));
            query.setOrderField("receiveTime");
            List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
            if (CollectionUtil.isNotNullOrEmpty(esOrderWorkList)) {
                orderWork.setChannelId(OrderConsts.CHANNEL_ID_PLAT_CHANNEL_B07);
                orderWork.setSourceChannelId(OrderConsts.CHANNEL_ID_PLAT_CHANNEL_B07);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderWorkAddress(OrderWork orderWork) {
        orderWorkService.updateOrderWorkAddressByKey(orderWork);
    }

    @Override
    public void updateOrderMasterSupervisor(Long orderId, Long workId, Integer masterId, Integer bizType, Integer servProductGroupId) {
        OrderWork updateWork = new OrderWork();
        updateWork.setOrderId(orderId);
        updateWork.setWorkId(workId);

        if (NumberUtil.isNotNullOrZero(masterId) && NumberUtil.isNotNullOrZero(servProductGroupId)) {
            // 查询并保存工程师主管
            // todo fubiao
            log.info("updateOrderMasterSupervisor#getSupervisorByEngineerIdAndBizType 入参 [{}] [{}] [{}] [{}]",workId,masterId,bizType,servProductGroupId);
            ResponseDTO<SupervisorViewDRO> remoteRespDTO = engineerSupervisorListRemoteService.getSupervisorByEngineerIdAndBizType(masterId, bizType, servProductGroupId);
            log.info("updateOrderMasterSupervisor#getSupervisorByEngineerIdAndBizType 出参 [{}]",JSON.toJSONString(remoteRespDTO));
            if (remoteRespDTO.isSuccess() && remoteRespDTO.getData() != null) {
                //EngineerSupervisorDRO engineerSupervisorDRO = remoteRespDTO.getData();
                SupervisorViewDRO engineerSupervisorDRO = remoteRespDTO.getData();
                updateWork.setMasterSupervisorId(engineerSupervisorDRO.getSupervisorId());
                updateWork.setMasterSupervisorName(engineerSupervisorDRO.getSupervisorName());
                updateWork.setMasterSupervisorPhone(engineerSupervisorDRO.getMobile());
            }
        }

        if (updateWork.getMasterSupervisorId() == null) {
            updateWork.setMasterSupervisorId(0);
            updateWork.setMasterSupervisorName("");
            updateWork.setMasterSupervisorPhone("");
        }
        orderWorkService.updateOrderMasterSupervisorByKey(updateWork);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderWork insertOrderWork(OrderWork orderWork) {

        if (StringUtil.isNotBlank(orderWork.getCurrentRemark())) {
            orderWork.setCurrentRemark(EmojiParser.parseToUnicode(orderWork.getCurrentRemark()));
        }

        orderWorkService.insertOrderWork(orderWork);
        return orderWork;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFinalPriceOrderToAfterPay(Long orderId) {
        // 修改一口价订单为后付
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        // 非进行中 不可修改
        if (!Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            log.error("#orderwork#updateFinalPriceOrderToAfterPay# orderId : {}, msg : {}", orderId, "非进行中 不可修改");
            return false;
        }

/*        // 非一口价订单 不可修改
        if (!Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
            log.error("#orderwork#updateFinalPriceOrderToAfterPay# orderId : {}, msg : {}", orderId, "非一口价订单 不可修改");
            return false;
        }*/

        // 啄木鸟预付款非支付中 不可修改
        if (!Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_ING)) {
            log.error("#orderwork#updateFinalPriceOrderToAfterPay# orderId : {}, msg : {}", orderId, "啄木鸟预付款非支付中 不可修改");
            return false;
        }

        // 清空啄木鸟预付 重新计算工程师收款金额
        WorkAmountDTO workAmountDTO = new WorkAmountDTO();
        workAmountDTO.setOrderId(orderId);
        workAmountDTO.setWorkId(orderId);
        workAmountDTO.setRemove(true);
        try {
            // 清空预付
            orderWorkAmountBService.updatePrepayAmount(workAmountDTO);
        } catch (Exception e) {
            log.error("#orderwork#updateFinalPriceOrderToAfterPay# orderId : {}, msg : {}", orderId, e.getMessage(), e);
            return false;
        }

        return true;
    }

    @Override
    public void checkPayUserId(OrderPayResultDRO orderPayResultDRO, Integer plat, Integer receiveEntranceId) {

        // 支付渠道非微信 设置
        Integer channelId = orderPayResultDRO.getPayChannelId();
        if (!Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_WEIXINPAY, channelId)) {
            OrderWork updateOrderWork = new OrderWork();
            updateOrderWork.setOrderId(orderPayResultDRO.getOrderId());
            updateOrderWork.setWorkId(orderPayResultDRO.getOrderId());
            updateOrderWork.setCustomerId((long) GlobalConsts.NONE);
            orderWorkService.updateCustomerUserId(updateOrderWork);
        } else {
            String openId = orderPayResultDRO.getPayerThirdAccount();
            Long orderId = orderPayResultDRO.getOrderId();

            Long customerId = 0L;
            try {
                // 注册用户

                // 渠道信息
                com.zmn.common.dto2.ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(GlobalConsts.CHANNEL_WEIXIN_ID);
                ChannelDRO channelDRO = channelResponseDTO.getData();

                // 可以绑定
                UserRegisterByThirdAccountDIO userRegisterByThirdAccountDIO = new UserRegisterByThirdAccountDIO();
                userRegisterByThirdAccountDIO.setOpenId(openId);
                userRegisterByThirdAccountDIO.setUnionId(openId);
                userRegisterByThirdAccountDIO.setPlat(plat);
                userRegisterByThirdAccountDIO.setUserName("支付用户");
                userRegisterByThirdAccountDIO.setGender(GlobalDict.GENDER_NO);
                userRegisterByThirdAccountDIO.setChannelId(GlobalConsts.CHANNEL_WEIXIN_ID);
                userRegisterByThirdAccountDIO.setChannelName(channelDRO.getName());
                userRegisterByThirdAccountDIO.setEntrance(receiveEntranceId);
                log.info("#oms#checkPayUserId#registerByThirdAccount 入参 ：userThirdInfoRegisterDIO:{}", JSON.toJSONString(userRegisterByThirdAccountDIO));

                // 修改调用uuc接口  xiewenbing  2020-11-16
                com.zmn.common.dto2.ResponseDTO<Long> registerDTO = userRegisterRemoteService.registerByThirdAccount(userRegisterByThirdAccountDIO);
                log.info("#oms#checkPayUserIdregisterByThirdAccount 出参 ： data:{}", JSON.toJSONString(registerDTO));
                if (!registerDTO.isSuccess() || registerDTO.getData() == null) {
                    log.error("#oms#checkPayUserId 注册失败 msg{}", registerDTO.getMessage());
                } else {
                    customerId = registerDTO.getData();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }


            // 修改 支付用户
            OrderWork updateOrderWork = new OrderWork();
            updateOrderWork.setOrderId(orderPayResultDRO.getOrderId());
            updateOrderWork.setWorkId(orderPayResultDRO.getOrderId());
            updateOrderWork.setCustomerId(customerId);
            orderWorkService.updateCustomerUserId(updateOrderWork);

            // 如果保修卡已经存在 但是用户id为空
            OrderWarranty orderWarranty = orderWarrantyService.findByOrderIdByKeySrcMaster(orderPayResultDRO.getOrderId());
            if (orderWarranty != null && NumberUtil.isNullOrZero(orderWarranty.getUserId())) {
                // 绑定用户
                orderWarrantyService.takeWarranty(orderId, customerId);
            }
        }
    }

    /**
     * 校验是否可以
     *
     * @param orderWork
     * @return
     */
    @Override
    public boolean checkCanChangeToRework(OrderWork orderWork) {
        // 新单&&没有已支付的金额
        return Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)
                && (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_NONE) || Objects.equals(orderWork.getPrepayStatus(), GlobalConsts.NONE))
                && (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_NONE) || Objects.equals(orderWork.getChannelPrepayStatus(), GlobalConsts.NONE))
                && (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_NONE) || Objects.equals(orderWork.getDepositStatus(), GlobalConsts.NONE))
                && (Objects.equals(orderWork.getPayStatus(), PayConsts.PAY_STATUS_NONE) || Objects.equals(orderWork.getPayStatus(), GlobalConsts.NONE))
                && (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_NONE) || Objects.equals(orderWork.getMasterPayStatus(), GlobalConsts.NONE));
    }

    @Override
    public boolean isWaitPrePay(OrderWork order) {

        // zmn 预付
        if (!NumberUtil.isNullOrZero(order.getPrepayAmount())) {
            if (!Objects.equals(PayConsts.PAY_STATUS_DONE, order.getPrepayStatus())) {
                return true;
            }
        }

        // 可弃单，不需要等待支付
        if (Objects.equals(order.getDisableDiscard(), GlobalConsts.NO) || Objects.isNull(order.getDisableDiscard())) {
            return false;
        }

        // 渠道预付有金额且已经支付，不需要等待支付
        if (!NumberUtil.isNullOrZero(order.getChannelPrepayAmount())) {
            if (Objects.equals(PayConsts.PAY_STATUS_DONE, order.getChannelPrepayStatus())) {
                return false;
            }
        }

        return true;
    }

}
